package com.cqqs.common.exception.handler;

import com.cqqs.common.bean.BaseRes;
import com.cqqs.common.constans.StringConstant;
import com.cqqs.common.enums.error.CommonErrorEnum;
import com.cqqs.common.exception.BusinessException;
import com.cqqs.common.exception.SystemException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * TODO
 *
 * @version: 1.0
 * @author: caijun.wei
 * @data: 2021/7/21 14:07
 */
@ControllerAdvice
public class GlobalExceptionHandler {
    Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(Exception.class)
    public BaseRes globalException(HttpServletResponse response, Exception ex) {
        if (ex instanceof BusinessException) {
            BusinessException businessException = (BusinessException) ex;
            BaseRes responseData = new BaseRes(businessException.getCode(), businessException.getMsg(), businessException.getData());

            return responseData;
        } else if (ex instanceof SystemException) {
            SystemException systemException = (SystemException) ex;
            BaseRes responseData = new BaseRes(systemException.getCode(), systemException.getMsg(), systemException.getData());
            return responseData;
        } else if (ex instanceof MethodArgumentNotValidException) {
            MethodArgumentNotValidException e = (MethodArgumentNotValidException) ex;
            String message = e.getBindingResult().getFieldError().getDefaultMessage();
            if (StringUtils.hasText(message)) {
                if (message.contains(StringConstant.SPECIAL_CHAR_THREE)) {
                    String[] messageArr = message.split(StringConstant.SPECIAL_CHAR_THREE);
                    int resultCode = Integer.parseInt(messageArr[0]);
                    String resultMsg = messageArr[1];
                    BaseRes responseData = new BaseRes(resultCode, resultMsg);
                    return responseData;
                }
            } else {
                BaseRes responseData = new BaseRes(CommonErrorEnum.SYSTEM_ERROR.getCode(), message);
                return responseData;
            }

        } else {
            log.error("服务器发送异常错误:" + ex.getMessage(), ex);
            BaseRes responseData = new BaseRes(CommonErrorEnum.SYSTEM_ERROR.getCode(), CommonErrorEnum.SYSTEM_ERROR.getMsg());
            return responseData;
        }
        return null;
    }
}